<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2018/12/24
 * Time: 6:39 PM
 */

namespace App\Api\Controllers\lianfu;


use App\Models\TfConfig;
use App\Models\TfStore;
use function EasyWeChat\Kernel\Support\get_client_ip;
use DefaultIcbcClient;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PayController extends BaseController
{

    //扫一扫 0-系统错误 1-成功 2-正在支付 3-失败
    public function scan_pay($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $code = $data['code'];
            $total_amount = $data['total_amount'];
            $order_amt=$total_amount*100;
            $mer_id=$data['apikey'];
            $post_data=array();
            $url = 'https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/pay/V4';
            //定义请求参数
            $biz_content=array(
                'qr_code'=>$code,
                'mer_id'=>$mer_id,
                'out_trade_no'=>$out_trade_no,
                'order_amt'=>"$order_amt",
                'trade_date'=>date("Ymd",time()),
                'trade_time'=>date("His",time()),
            );

            //单品
            $isGoods = 2;
            if (isset($data['store_id']) && !empty($data['store_id'])) {
                $isGoods =  \App\Models\Store::where('store_id', $data['store_id'])->value('is_goods');
            }
            if (isset($data['goods_detail']) && !empty($data['goods_detail'])) {
                error_log(date('Y-m-d H:i:s')." 【工行单品】： ".json_encode([$data['goods_detail'], $isGoods])."\n\n", 3, "/www/wwwlogs/wft/". 'goods-icbc'.date('Ymd').".log");
            }

            if (isset($data['goods_detail']) && !empty($data['goods_detail']) && $isGoods == 1) {
                $goods = json_decode($data['goods_detail'], true);
                $goodsArr = [];
                foreach ($goods['goods_detail'] as $v) {
                    $goodsArr[] = [
                        'quantity'  => $v['quantity'],
                        'goods_id'   => $v['goods_id'],
                        'price'     => (int)$v['price'],
                        'goods_name' => $v['goods_name'],
                    ];
                }
                $biz_content['goods_detail'] = $goodsArr;
                error_log(date('Y-m-d H:i:s')." 【工行单品】： ".json_encode([$biz_content, $isGoods])."\n\n", 3, "/www/wwwlogs/wft/". 'goods-icbc'.date('Ymd').".log");
            }

            //组装参数
            $post_data=array('app_id'=>$data['appid'],'sign_type'=>'RSA2','charset'=>'UTF-8','format'=>'json','msg_id'=>time(),'timestamp'=>date("Y-m-d H:i:s",time()),'biz_content'=>json_encode($biz_content));
            $obj = new BaseController();
            //排序并拼接待签名字符串
            $respBizContentStr = $obj->buildOrderedSignStr('/api/mybank/pay/qrcode/scanned/pay/V4',$post_data);
            //私钥加密
            $prikey=$data['signkey'];
            openssl_sign($respBizContentStr,$signature,"-----BEGIN PRIVATE KEY-----\n".$prikey."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA256);
            $post_data['sign'] =base64_encode($signature);
            $re = $this->doPost($url, $post_data,'UTF-8');
            Log::channel("lianfu")->info("scan_pay",[
                "url"=>$url,
                "req"=>$post_data,
                "res"=>$re
            ]);
            $re = json_decode($re, true);
            //交易成功
            if ($re['response_biz_content']['pay_status'] == '1') {
                 \App\Common\PaySuccessAction::addCoupon($out_trade_no, $re['response_biz_content'], 'pay');
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re['response_biz_content'],
                ];
            } //用户输入密码
            elseif ($re['response_biz_content']['pay_status'] == '0') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re['response_biz_content'],
                ];

            } else {
                return [
                    'status' => 3,
                    'message' => $re['response_biz_content'],
                ];
            }


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }


    //安徽农金支付
    public function scan_pay1($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $code = $data['code'];
            $total_amount = $data['total_amount'];
            $signkey = $data['signkey'];
            $merchantNo=$data['merchantNo'];
            $terminalNo=$data['terminalNo'];
            $batchNo=$data['batchNo'];
            $post_data = array(
                'transAmount' => intval($total_amount * 100),
                'outTradeNo' => $out_trade_no,
                'traceNo' => $batchNo,
                'merchantNo'=>$merchantNo,
                'terminalNo'=>$terminalNo,
                'batchNo'=>$batchNo,
                'notifyUrl'=>'https://pay.zgjindoufu.com/api/wincode/nongjin_notify',
                'payCode'=>$code,
                'nonceStr'=>$this->nonceStr()
            );
//            file_put_contents('sdgsdg3.log',var_export($post_data,true)."\r\n",FILE_APPEND);
            $obj = new BaseController();
            $string = $obj->getSignContent($post_data);
            $string = $string . '&key=' . $signkey;
            $sign = strtoupper(md5($string));
            $post_data['sign'] = $sign;
            $url = 'https://epos.ahrcu.com:3443/cposp/pay/microPay';
//            file_put_contents('sdgsdg3.log',var_export(json_encode($post_data),true)."\r\n",FILE_APPEND);
//            Log::channel("pay")->info("nongjing_curl_before_:",$post_data);
            $re = $this->http_curl3($url, json_encode($post_data));
            Log::channel("nongjin")->info("scan_pay1-res".$out_trade_no,[
                "res"=>$re
            ]);
//            Log::channel("pay")->info("nongjing_curl_after_:",[$re]);
//            file_put_contents('sdgsdg3.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);
            Log::channel("nongjin")->info("scan_pay1-".$out_trade_no,[
                "req"=>$post_data,
                "res"=>$re
            ]);
            if(!$re){
                return [
                        'status' => 2,
                        'message' => '请用户输入密码',
                        'data' => $re,
                    ];
            }
            //交易成功
            if($re['resultCode']==00){
                if ($re['orderStatus'] == 3) {
                    return [
                        'status' => 1,
                        'message' => '交易成功',
                        'data' => $re,
                    ];
                } //用户输入密码
                elseif ($re['orderStatus'] == 2) {
                    return [
                        'status' => 2,
                        'message' => '请用户输入密码',
                        'data' => $re,
                    ];

                } else {
                    return [
                        'status' => 3,
                        'message' => $re,
                    ];
                }
            }else{
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re,
                ];
            }


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //查询订单 0-系统错误 1-成功 2-正在支付 3-失败 4.已经退款 5 退款中
    public function order_query_mini($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            // $code = $data['code'];
            $total_amount = $data['total_amount'];
            $order_amt=$total_amount*100;
            $mer_id=$data['apikey'];
            $post_data=array();
            $url = 'https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/orderqry/V1';
            //定义请求参数
            $biz_content=array(
                'mer_id'=>$mer_id,
                'out_trade_no'=>$out_trade_no,
                'deal_flag'=>'0',
                'icbc_appid'=>$data['appid']
            );
            //组装参数
            $post_data=array('app_id'=>$data['appid'],'sign_type'=>'RSA2','charset'=>'UTF-8','format'=>'json','msg_id'=>time(),'timestamp'=>date("Y-m-d H:i:s",time()),'biz_content'=>json_encode($biz_content));
            $obj = new BaseController();
            //排序并拼接待签名字符串
            $respBizContentStr = $obj->buildOrderedSignStr('/api/cardbusiness/aggregatepay/b2c/online/orderqry/V1',$post_data);
            //私钥加密
            $prikey=$data['signkey'];
            openssl_sign($respBizContentStr,$signature,"-----BEGIN PRIVATE KEY-----\n".$prikey."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA256);
            $post_data['sign'] =base64_encode($signature);
            file_put_contents('icbcce14.log',var_export($post_data,true)."\r\n",FILE_APPEND);
            $re = $this->doPost($url, $post_data,'UTF-8');
            $re = json_decode($re, true);
            //交易成功
            if ($re['response_biz_content']['pay_status'] == '0') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re['response_biz_content'],
                ];
            } //用户输入密码
            elseif ($re['response_biz_content']['pay_status'] == '2') {
                return [
                    'status' => 2,
                    'message' => '支付中',
                    'data' => $re['response_biz_content'],
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re['response_biz_content'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //甘肃农金支付
    public function scan_pay5($data)
    {
        try {
            $obj = new BaseController();
            $Xmldata = $obj->getXmlContent($data);
            $sign=$obj->createSign1($Xmldata);
            $Signature=$sign;
            $url = 'http://test.unionpay.gsrcu.com:9080/QRC/TJSK.do';
            $post_data=[];
            $post_data['Plain']=$Xmldata;
            $post_data['Signature']=$Signature;
            $re = $this->gshttp_curl($url, $post_data);
            $re = json_decode($re, true);
            //交易成功
            if ($re['TransStatus'] == 'S') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re,
                ];
            } //用户输入密码
            elseif ($re['TransStatus'] == 'W') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re,
                ];

            } else {
                return [
                    'status' => 3,
                    'message' => $re,
                ];
            }


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //翼支付
    public function scan_pay22($data, $url)
    {
        try {
            $obj = new BaseController();
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $data['sign'] = $sign;
            $post_data=json_encode($data);

            $re = $this->http_curl($url, $post_data);
            // file_put_contents('yi1.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);
            return $re;

        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //翼支付
    public function scan_pay2($data)
    {
        try {
            $obj = new BaseController();
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $data['sign'] = $sign;
            $url = 'https://mapi.bestpay.com.cn/mapi/aggregatepay/offline/b2c/pay';
            $post_data=json_encode($data);
            file_put_contents('yi1.log',var_export($post_data,true)."\r\n",FILE_APPEND);
            $re = $this->http_curl($url, $post_data);
            file_put_contents('yi1.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);
            //交易成功
            if ($re['errorCode'] == '000000') {
                if($re['result']['tradeStatus']=='SUCCESS'){
                    return [
                        'status' => 1,
                        'message' => '交易成功',
                        'data' => $re,
                    ];
                }else if($re['result']['tradeStatus']=='WAITFORPAY'){
                    return [
                        'status' => 2,
                        'message' => '请用户输入密码',
                        'data' => $re,
                    ];
                }else{
                    return [
                        'status' => 3,
                        'message' => $re,
                    ];
                }
            }else{
                return [
                    'status' => 3,
                    'message' => $re,
                ];
            }

        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //翼支付进件
    public function uploadFiles($data,$url){
        $obj = new BaseController();
        $string = $obj->getSignContent($data);
        $sign=$this->createSigng($string);
        $data['sign']=$sign;
        $data=json_encode($data,JSON_UNESCAPED_SLASHES);

        $key='KrglKECpfXvOpGY3';
        $encryptData = openssl_encrypt($data, 'AES-128-CBC', $key,0,'b2owNVVDUllYT2I=');
        $encryptKey=$this->createSignf($key);//aeskey进行RSA加密
        $array=array(
            'encryptData'=>$encryptData,
            'encryptKey'=>$encryptKey,
            'merchantNo'=>'3178035630163868'
        );

        $re = $this->http_curl($url, json_encode($array,JSON_UNESCAPED_SLASHES));
        $re=json_decode($re,true);
        return $re['result'];
    }

    //翼支付进件
    public function merchantIntegrateInput($data,$url){
        $obj = new BaseController();
        $string = $obj->getSignContent($data);
        $sign=$this->createSigng($string);
        $data['sign']=$sign;
        file_put_contents('b235235.log',var_export($data,true)."\r\n",FILE_APPEND);
        $data=json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        $key='KrglKECpfXvOpGY3';
        file_put_contents('b235235.log',var_export($data,true)."\r\n",FILE_APPEND);
        $encryptData = openssl_encrypt($data, 'AES-128-CBC', $key,0,'b2owNVVDUllYT2I=');

        $encryptKey=$this->createSignf($key);//aeskey进行RSA加密
        $array=array(
            'encryptData'=>$encryptData,
            'encryptKey'=>$encryptKey,
            'merchantNo'=>'3178035630163868'
        );
        error_log(date('Y-m-d H:i:s')." 【翼支付进件资料1】： ".json_encode($data)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");

        error_log(date('Y-m-d H:i:s')." 【翼支付进件资料1】： ".json_encode($array)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");

        file_put_contents('b3223.log',var_export($array,true)."\r\n",FILE_APPEND);
        $re = $this->http_curl($url, json_encode($array,JSON_UNESCAPED_SLASHES));
        $re=json_decode($re,true);
        file_put_contents('b3223.log',var_export($re,true)."\r\n",FILE_APPEND);
        if($re['success']=='1'){
            $str = mb_convert_encoding($re['result']['encryptKey'], 'UTF-8');
            $strData = mb_convert_encoding($re['result']['encryptData'], 'UTF-8');
            $decoded = base64_decode(str_replace(' ', '+', $str));
            $encryptKey=$this->createSignj($decoded);//aeskey进行RSA加密
            $data1 = openssl_decrypt($strData, 'AES-128-CBC', $encryptKey,0, 'b2owNVVDUllYT2I=');
            $data1=json_decode($data1,true);
            $data1['success']=1;
            error_log(date('Y-m-d H:i:s')." 【翼支付进件资料2】： ".json_encode($data1)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");

            return json_encode($data1);
        }else{
             return json_encode($re);
        }
    }

    //翼支付进件查询
    public function queryMerchantInputStatus($data,$url){
        $obj = new BaseController();
        $string = $obj->getSignContent($data);
        $sign=$this->createSigng($string);
        $data['sign']=$sign;

        $data=json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

        $key='KrglKECpfXvOpGY3';
        $encryptData = openssl_encrypt($data, 'AES-128-CBC', $key,0,'b2owNVVDUllYT2I=');

        $encryptKey=$this->createSignf($key);//aeskey进行RSA加密
        $array=array(
            'encryptData'=>$encryptData,
            'encryptKey'=>$encryptKey,
            'merchantNo'=>'3178035630163868'
        );

        error_log(date('Y-m-d H:i:s')." 【翼支付进件查询】： ".json_encode([$data, $array])."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
        $re = $this->http_curl($url, json_encode($array,JSON_UNESCAPED_SLASHES));
        $re=json_decode($re,true);
        error_log(date('Y-m-d H:i:s')." 【翼支付进件查询rs】： ".json_encode($re)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");


        $str = mb_convert_encoding($re['result']['encryptKey'], 'UTF-8');
        $strData = mb_convert_encoding($re['result']['encryptData'], 'UTF-8');
        $decoded = base64_decode(str_replace(' ', '+', $str));
        $encryptKey=$this->createSignj($decoded);//aeskey进行RSA加密
        $data1 = openssl_decrypt($strData, 'AES-128-CBC', $encryptKey,0, 'b2owNVVDUllYT2I=');
        file_put_contents('b12412.log',var_export($data1,true)."\r\n",FILE_APPEND);
        return $data1;
    }

    //翼支付进件签约
    public function productContract($data,$url){
        $obj = new BaseController();
        $string = $obj->getSignContent($data);
        $sign=$this->createSigng($string);
        $data['sign']=$sign;

        $data=json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

        $key='KrglKECpfXvOpGY3';
        $encryptData = openssl_encrypt($data, 'AES-128-CBC', $key,0,'b2owNVVDUllYT2I=');

        $encryptKey=$this->createSignf($key);//aeskey进行RSA加密
        $array=array(
            'encryptData'=>$encryptData,
            'encryptKey'=>$encryptKey,
            'merchantNo'=>'3178035630163868'
        );
        $re = $this->http_curl($url, json_encode($array,JSON_UNESCAPED_SLASHES));
        file_put_contents('b771665.log',var_export($re,true)."\r\n",FILE_APPEND);
        $re=json_decode($re,true);
        if(isset($re['errorCode'])){
            return $re;
        }else{
            $str = mb_convert_encoding($re['result']['encryptKey'], 'UTF-8');
            $strData = mb_convert_encoding($re['result']['encryptData'], 'UTF-8');
            $decoded = base64_decode(str_replace(' ', '+', $str));
            $encryptKey=$this->createSignj($decoded);//aeskey进行RSA加密
            $data1 = openssl_decrypt($strData, 'AES-128-CBC', $encryptKey,0, 'NzhSQm90T3JTdzU=');
            return $data1;
        }
    }

    //翼支付进件签约查询
    public function queryProductSignResult($data,$url){
        $obj = new BaseController();
        $string = $obj->getSignContent($data);
        $sign=$this->createSigng($string);
        $data['sign']=$sign;

        $data=json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

        $key='KrglKECpfXvOpGY3';
        $encryptData = openssl_encrypt($data, 'AES-128-CBC', $key,0,'b2owNVVDUllYT2I=');

        $encryptKey=$this->createSignf($key);//aeskey进行RSA加密
        $array=array(
            'encryptData'=>$encryptData,
            'encryptKey'=>$encryptKey,
            'merchantNo'=>'3178035630163868'
        );
        $re = $this->http_curl($url, json_encode($array,JSON_UNESCAPED_SLASHES));
        echo '<pre>';
        print_r($re);
        die;
        $re=json_decode($re,true);
        $str = mb_convert_encoding($re['result']['encryptKey'], 'UTF-8');
        $strData = mb_convert_encoding($re['result']['encryptData'], 'UTF-8');
        $decoded = base64_decode(str_replace(' ', '+', $str));
        $encryptKey=$this->createSignj($decoded);//aeskey进行RSA加密
        $data1 = openssl_decrypt($strData, 'AES-128-CBC', $encryptKey,0, 'b2owNVVDUllYT2I=');
        return $data1;
    }

    //翼支付私钥解密
    public function createSignj($aesKey){
        $pfx=file_get_contents('https://pay.zgjindoufu.com/安徽淮风文化传媒有限公司.P12');
        $cert_info=array();
        $priKey=openssl_pkcs12_read($pfx,$cert_info,'97445505');
        if (!is_string($aesKey)) {
            return null;
        }
        $pkey=openssl_pkey_get_private($cert_info['pkey']);
        openssl_private_decrypt($aesKey, $decrypted, $pkey);
        return $decrypted;
    }

    //翼支付私钥加密
    public function createSignf($aesKey){
        $publicKey = '-----BEGIN CERTIFICATE-----
MIICZDCCAc+gAwIBAgIECNrXMDALBgkqhkiG9w0BAQUwMzELMAkGA1UEBhMCQ04x
JDAiBgNVBAMMG2Jlc3RwYXkgY2Egb25saW5lY2FfUlNBcm9vdDAeFw0yMTA1MTcx
NjAwMDBaFw0yNDA1MTcxNjAwMDBaMGQxCzAJBgNVBAYTAkNOMRAwDgYDVQQKDAdC
RVNUUEFZMScwJQYDVQQDDB7lpKnnv7znlLXlrZDllYbliqHmnInpmZDlhazlj7gx
GjAYBgNVBAUTETIwMjEwNTE4MTUzMTU3NDQ5MIGdMAsGCSqGSIb3DQEBAQOBjQAw
gYkCgYEAmwL5uX1v7dK00JraeYi2f+9UQHuwqeT2Lwuntbj5zLT50TXy2lSGjAnH
tKboQz9ahpbTIVotuHCygufROr8S5QPGiIOrA6dtCeRMJkAM9PO3feY59O+1op6r
z19HiMUc81vo9elePs1vBFjy2+1hjC7tK/+DPcS20DTUXSwMTs0CAwEAAaNaMFgw
HwYDVR0jBBgwFoAU3uYiedkx4p9GitScsGH1myw+T0wwCwYDVR0PBAQDAgeAMB0G
A1UdDgQWBBR5R/zIrvleeP7KDI7B0v3WdNiYsDAJBgNVHRMEAjAAMAsGCSqGSIb3
DQEBBQOBgQBLFea7Q2BeeZY+YHLckfvBlATaZck15Z+fPXMEydmmIr7ON5l0xZWq
Y7IhkjLquftnSJ7GiNTEiws6Y0VQ/ipiTlnUOX2+vHm5mWJ6xAcIgDGoQBG4M6iz
pJeYRzMQLRyut6yC8rcZdD7fQUtxDIfcY6ntzdJpU7wv2DQR+K57Tw==
-----END CERTIFICATE-----';
        $encrypted = '';
        $publicKeyResource = openssl_get_publickey($publicKey);
        $f = openssl_public_encrypt($aesKey, $encrypted, $publicKeyResource);
        openssl_free_key($publicKeyResource);
        if ($f) {
            return base64_encode($encrypted);
        }
        return null;
    }

    //翼支付私钥加密
    public function createSigng($data){
        $pfx=file_get_contents('https://pay.zgjindoufu.com/安徽淮风文化传媒有限公司.P12');
        $cert_info=array();
        $priKey=openssl_pkcs12_read($pfx,$cert_info,'97445505');

        openssl_sign($data, $sign, $cert_info['pkey'],OPENSSL_ALGO_SHA256);
        return base64_encode($sign);
    }

    //翼支付私钥加密
    public function createSign($data){
        $pfx=file_get_contents('https://pay.zgjindoufu.com/安徽淮风文化传媒有限公司.P12');
        $cert_info=array();
        $priKey=openssl_pkcs12_read($pfx,$cert_info,'97445505');

        openssl_sign($data, $sign, $cert_info['pkey'],OPENSSL_ALGO_SHA256);
        return base64_encode($sign);
    }

     //建行支付
    public function scan_pay_ccb($data,$pubkey)
    {
        try {
            $obj = new BaseController();
            $sign = $obj->calSign($obj->sortParams($data));
            $data['SIGN'] = $sign;
            // $string = $obj->sortParams($data);
            $params = http_build_query($data);
            $pubKey = substr($pubkey, -30);
            $pubKey = substr($pubKey, 0, 8);
            $data['ccbParam'] = $obj->calCcbParam($params, $pubKey);
            $url = 'https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00_BEPAY'. '?' . http_build_query($data);
            $re = $this->http_curl($url, json_encode($data));
            $re = json_decode($re, true);
             file_put_contents('ccb.log',var_export($re,true)."\r\n",FILE_APPEND);
            //交易成功
            if ($re['RESULT'] == 'Y') {
                \App\Common\PaySuccessAction::addCoupon($data['ORDERID'], $re, 'pay');
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re,
                ];
            }else if($re['RESULT']=='Q'){
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re,
                ];
            }else{
                return [
                    'status' => 3,
                    'message' => $re,
                ];
            }

        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //更新翼支付商户状态
    public function upwingmerch($data)
    {
        try {
            $obj = new BaseController();
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $data['sign'] = $sign;
            $url = 'https://mapi.bestpay.com.cn/mapi/provinceReceipt/updateServiceNo';
            $post_data=json_encode($data);
            $re = $this->http_curl($url, $post_data);
            $re = json_decode($re, true);
        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //扫呗支付
    public function scan_pay3($data,$token)
    {
        try {
            $obj = new BaseController();
            $string = $obj->getSignContent1($data);
            $string = $string . '&access_token=' . $token;
            $sign = md5($string);
            $data['key_sign'] = $sign;
            $data['terminal_ip'] = $_SERVER['REMOTE_ADDR'];//交易终端IP
            $url = 'https://pay.lcsw.cn/lcsw/pay/100/barcodepay';
            $re = $this->http_curl($url, json_encode($data));
            $re = json_decode($re, true);
            //交易成功
            if ($re['result_code'] == '01') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re,
                ];
            } //用户输入密码
            elseif ($re['result_code'] == '03') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re,
                ];

            } else {
                return [
                    'status' => 3,
                    'message' => $re,
                ];
            }


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //通联支付
    public function allin_pay($data,$prikey)
    {
        try {
            $obj = new BaseController();
            $sign=$obj->allin_sign($data,$prikey);
            $data['sign'] = urlencode($sign);
            $dataStr=$obj->allin_Params($data);
            $url = 'https://vsp.allinpay.com/apiweb/unitorder/scanqrpay';
            error_log(date('Y-m-d H:i:s') . "\t----xxx----:". json_encode($data) . "\n", 3, "/tmp/test".date('Ymd').".log");
            $re = $this->allin_request($url, $dataStr);
            $re = json_decode($re, true);
            error_log(date('Y-m-d H:i:s') . "\t----xxx----:". json_encode($re) . "\n", 3, "/tmp/test".date('Ymd').".log");
            //交易成功
            if ($re['trxstatus'] == '0000') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re,
                ];
            } //用户输入密码
            elseif ($re['trxstatus'] == '2008' || $re['trxstatus'] == '2000') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re,
                ];

            } else {
                return [
                    'status' => 3,
                    'message' => $re,
                ];
            }


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //酷点支付
    public function scan_pay4($data)
    {
        try {
            $obj = new BaseController();
            $url = 'https://pay.kudianvip.com/openapi/pay/micropay';
            $re = $this->http_curl($url, json_encode($data));
            $re = json_decode($re, true);
            $result=json_decode($re['result'], true);
            //交易成功
            if ($result['status'] == '100') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $result
                ];
            } //用户输入密码
            elseif ($result['status'] == '102' || $result['status'] == '101') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $result
                ];

            } else {
                return [
                    'status' => 3,
                    'message' => $result
                ];
            }


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //平安银行
    public function scan_pay6($data)
    {
        try {
            $obj = new BaseController();
            $url = 'http://www.vipspt.cn/payOpen/bToC';
            $re = $this->http_curl($url, $data);
            $result=json_decode($re, true);
            //交易成功
            if($result['ret'] == '0'){
                if ($result['data']['status'] == '2') {
                    return [
                        'status' => 1,
                        'message' => '交易成功',
                        'data' => $result['data']
                    ];
                } //用户输入密码
                elseif ($result['data']['status'] == '0') {
                    return [
                        'status' => 2,
                        'message' => '请用户输入密码',
                        'data' => $result['data']
                    ];

                }else {
                    return [
                        'status' => 3,
                        'message' => $result['data']
                    ];
                }
            }else{
                return [
                    'status' => 3,
                    'message' => $result['msg']
                ];
            }


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //平安银行
    public function postpingan($data)
    {
        try {

            $obj = new BaseController();
            $url = 'http://www.vipspt.cn/payOpen/pluginNotifications';
            $re = $this->http_curl22($url, $data);
            $result=json_decode($re, true);
            return 1;


        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }

    //查询订单 0-系统错误 1-成功 2-正在支付 3-失败 4.已经退款 5 退款中
    public function order_query($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            // $code = $data['code'];
            $total_amount = $data['total_amount'];
            $order_amt=$total_amount*100;
            $mer_id=$data['apikey'];
                                                                // file_put_contents('ceshi.log',var_export(111,true)."\r\n",FILE_APPEND);
            $post_data=array();
            $url = 'https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/paystatus/V3';
            //定义请求参数
            $biz_content=array(
                'mer_id'=>$mer_id,
                'out_trade_no'=>$out_trade_no,
                'trade_date'=>date("Ymd",time()),
                'deal_flag'=>'0',
            );
            //组装参数
            $post_data=array('app_id'=>$data['appid'],'sign_type'=>'RSA2','charset'=>'UTF-8','format'=>'json','msg_id'=>time(),'timestamp'=>date("Y-m-d H:i:s",time()),'biz_content'=>json_encode($biz_content));
            $obj = new BaseController();
            //排序并拼接待签名字符串
            $respBizContentStr = $obj->buildOrderedSignStr('/api/mybank/pay/qrcode/scanned/paystatus/V3',$post_data);
            //私钥加密
            $prikey=$data['signkey'];
            openssl_sign($respBizContentStr,$signature,"-----BEGIN PRIVATE KEY-----\n".$prikey."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA256);
            $post_data['sign'] =base64_encode($signature);
            $re = $this->doPost($url, $post_data,'UTF-8');
            Log::channel("lianfu")->info("order_query",[
                "url"=>$url,
                "req"=>$post_data,
                "res"=>$re
            ]);
            // file_put_contents('ceshi.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);

            //交易成功
            if ($re['response_biz_content']['pay_status'] == '1') {
                \App\Common\PaySuccessAction::addCoupon($out_trade_no, $re['response_biz_content'], 'query');
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re['response_biz_content'],
                ];
            } //用户输入密码
            elseif ($re['response_biz_content']['pay_status'] == '0') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re['response_biz_content'],
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re['response_biz_content'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

     //静态码提交-公共
    public function qr_submit1($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $total_amount = $data['total_amount'];
            $ways_type = $data['ways_type'];
            $open_id = $data['open_id'];
            $order_amt=$total_amount*100;
            $mer_id=$data['apikey'];
            $post_data=array();
            $url = 'https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1';
            if($ways_type=='20001'){
                $pay_mode='10';
                $access_type='8';
            }else if($ways_type=='20002'){
                $pay_mode='9';
                $access_type='7';
            }else if($ways_type=='20004'){
                $pay_mode='13';
                $access_type='5';
            }
            //定义请求参数
            $biz_content=array(
                'mer_id'=>$mer_id,
                'mer_prtcl_no'=>$mer_id,
                'out_trade_no'=>$out_trade_no,
                'pay_mode'=>$pay_mode,
                'access_type'=>$access_type,
                'orig_date_time'=>date("Y-m-d",time()).'T'.date("H:i:s",time()),
                'decive_info'=>'123456',
                'body'=>'日常百货',
                'fee_type'=>'001',
                'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
                'total_fee'=>"$order_amt",
                'notify_type'=>"HS",
                'mer_url'=>url('api/wincode/icbc_callback1'),
                'icbc_appid'=>$data['appid'],
                'notify_url'=>url('api/wincode/icbc_callback1')
            );
            if($ways_type=='20001'){
                $biz_content['union_id']=$open_id;
            }else if($ways_type=='20002'){
                $biz_content['open_id']=$open_id;
                $biz_content['shop_appid']='wx5217ac6570504684';
            }else if($ways_type=='20004'){

            }
            //组装参数
            $post_data=array('app_id'=>$data['appid'],'sign_type'=>'RSA2','charset'=>'UTF-8','format'=>'json','msg_id'=>time(),'timestamp'=>date("Y-m-d H:i:s",time()),'biz_content'=>json_encode($biz_content));
            $obj = new BaseController();
            //排序并拼接待签名字符串
            $respBizContentStr = $obj->buildOrderedSignStr('/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1',$post_data);
            //私钥加密
            $prikey=$data['signkey'];
            openssl_sign($respBizContentStr,$signature,"-----BEGIN PRIVATE KEY-----\n".$prikey."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA256);
            $post_data['sign'] =base64_encode($signature);
            $re = $this->doPost($url, $post_data,'UTF-8');
            $re = json_decode($re, true);
            //error_log(date('Y-m-d H:i:s')." 【工行主扫返回】： ".$re."\n\n", 3, "/tmp/". 'icbc'.date('Ymd').".log");

            //系统错误
            if ($re['response_biz_content']['return_code'] != "0") {
                return [
                    'status' => 0,
                    'message' => $re['response_biz_content']['return_msg']
                ];
            }
            if($ways_type=='20001'){
                $package=$re['response_biz_content']['zfb_data_package'];
            }else if($ways_type=='20002'){
                $package=json_decode($re['response_biz_content']['wx_data_package'],true);
            }

            //如果是失败报备一下
            if ($re['response_biz_content']['return_code'] == "0") {
                return [
                    'status' => 1,
                    'message' => '返回成功',
                    'data' => $package

                ];
            }
        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //农商行查询订单
    public function order_query2($data)
    {
        try {
            $out_trade_no = $data['outTradeNo'];
            // $total_amount = $data['total_amount'];
            $signkey = $data['signkey'];
            $merchantNo=$data['merchantNo'];
            $terminalNo=$data['terminalNo'];
            $batchNo=$data['batchNo'];
            $post_data = array(
                'outTradeNo' => $out_trade_no,
                'traceNo' => $batchNo,
                'merchantNo'=>$merchantNo,
                'terminalNo'=>$terminalNo,
                'batchNo'=>$batchNo,
                'nonceStr'=>$this->nonceStr()
            );
             //error_log(date('Y-m-d H:i:s')." 【农商行查询】： ".json_encode([$post_data, $signkey])."\n\n", 3, "/www/wwwlogs/wft/". 'nsh'.date('Ymd').".log");

//            file_put_contents('sdgsdg3.log',var_export($post_data,true)."\r\n",FILE_APPEND);
            $obj = new BaseController();
            $string = $obj->getSignContent($post_data);
            $string = $string . '&key=' . $signkey;
            $sign = strtoupper(md5($string));
            $post_data['sign'] = $sign;
            $url = 'https://epos.ahrcu.com:3443/cposp/pay/orderQuery';
            $re = $this->http_curl3($url, json_encode($post_data));
//            error_log(date('Y-m-d H:i:s')." 【农商行查询】： ".json_encode([$post_data, $signkey, $re])."\n\n", 3, "/www/wwwlogs/wft/". 'nsh'.date('Ymd').".log");
            Log::channel("nongjin")->info("农商行查询",[
                "url"=>$url,
                "req"=>$post_data,
                "res"=>$re
            ]);
            $re = json_decode($re, true);
            if(!$re ||$re['resultCode']=='C4'){
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re,
                ];
            }
            //交易成功
            if ($re['orderStatus'] == '3') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re,
                ];
            } //用户输入密码
            elseif ($re['orderStatus'] == '2') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re,
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re,
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //翼支付公众号支付
    public function wingqr_submit($data){
        try {
            $obj = new BaseController();
            $post_data=$data;
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $post_data['sign'] = $sign;
            $url = 'https://mapi.bestpay.com.cn/mapi/aggregatepay/offline/c2b/payOrder';
            $re = $this->http_curl($url, json_encode($post_data));
            $re = json_decode($re, true);
            //交易成功
            if ($re['errorCode'] == '000000') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re['result'],
                ];
            }else{
                return [
                    'status' => 2,
                    'message' => '交易失败',
                    'data' => $re['result'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //平安银行主扫
    public function safeqr_submit($data){
        try {
            $obj = new BaseController();
            $url = 'http://www.vipspt.cn/payOpen/order';
            $result = $this->http_curl($url, $data);
            file_put_contents('pingzhu.log',var_export($result,true)."\r\n",FILE_APPEND);
            $result=json_decode($result, true);
            //交易成功
            if ($result['data']['status'] == '0') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $result['data']
                ];

            }else {
                 return [
                    'status' => 2,
                    'message' => '交易失败',
                    'data' => $result['data'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //翼支付查询订单
    public function order_query1($data)
    {
        try {
            $obj = new BaseController();
            $post_data=$data;
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $post_data['sign'] = $sign;
            $url = 'https://mapi.bestpay.com.cn/mapi/aggregatepay/tradeQuery';
            $re = $this->http_curl($url, json_encode($post_data));
            file_put_contents('yi2.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);

            //交易成功
            if ($re['result']['tradeStatus'] == 'SUCCESS') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re['result'],
                ];
            } //用户输入密码
            elseif ($re['result']['tradeStatus'] == 'WAITFORPAY') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re['result'],
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re['result'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //扫呗查询订单
    public function order_query3($data,$token)
    {
        try {
            $obj = new BaseController();
            $string = $obj->getSignContent1($data);
            $string = $string . '&access_token=' . $token;
            $sign = md5($string);
            $data['key_sign'] = $sign;
                        // file_put_contents('sao.log',var_export($data,true)."\r\n",FILE_APPEND);
            $url = 'https://pay.lcsw.cn/lcsw/pay/100/query';
            $re = $this->http_curl($url, json_encode($data));
            $re = json_decode($re, true);

            //交易成功
            if ($re['result_code'] == '01') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re
                ];
            } //用户输入密码
            elseif ($re['result_code'] == '03') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //建行查询订单
    public function order_query_ccb($data,$pubkey)
    {
        try {
            $data['RETURN_FIELD']='11111100000000000000';
            $obj = new BaseController();
            $sign = $obj->calSign($obj->sortParams($data));
            $data['SIGN'] = $sign;
            $params = http_build_query($data);
            $pubKey = substr($pubkey, -30);
            $pubKey = substr($pubKey, 0, 8);
            $data['ccbParam'] = $obj->calCcbParam($params, $pubKey);
            $url = 'https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00_BEPAY'. '?' . http_build_query($data);
            $re = $this->http_curl($url, json_encode($data));
            $re = json_decode($re, true);
            //交易成功
            if ($re['RESULT'] == 'Y') {
                \App\Common\PaySuccessAction::addCoupon($data['ORDERID'], $re, 'query');
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re
                ];
            } //用户输入密码
            elseif ($re['RESULT'] == 'Q') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //通联支付查询订单
    public function allin_search($data,$prikey)
    {
        try {
            $obj = new BaseController();
            $sign=$obj->allin_sign($data,$prikey);
            $data['sign'] = urlencode($sign);
            $dataStr=$obj->allin_Params($data);
            $url = 'https://vsp.allinpay.com/apiweb/tranx/query';
            $re = $this->allin_request($url, $dataStr);
            $re = json_decode($re, true);

            //交易成功
            if ($re['trxstatus'] == '0000') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re
                ];
            } //用户输入密码
            elseif ($re['trxstatus'] == '2008' || $re['trxstatus'] == '2000' ) {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //酷点查询订单
    public function order_query4($data)
    {
        try {
            $obj = new BaseController();
            $url = 'https://pay.kudianvip.com/openapi/pay/query';
            $re = $this->http_curl($url, json_encode($data));
            $re = json_decode($re, true);
            $result=json_decode($re['result'], true);
            //交易成功
            if ($result['status'] == '100') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $result
                ];
            } //用户输入密码
            elseif ($result['status'] == '102'|| $result['status'] == '101') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $result
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $result
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //平安银行-查询订单
    public function order_query6($data)
    {
        try {
            $obj = new BaseController();
            $url = 'http://www.vipspt.cn/payOpen/query';
            $re = $this->http_curl($url, $data);
            file_put_contents('pingansearch.log',var_export($re,true)."\r\n",FILE_APPEND);
            $result=json_decode($re, true);
            //交易成功
            if ($result['ret'] == '0') {
                if ($result['data']['status'] == '2') {
                    return [
                        'status' => 1,
                        'message' => '交易成功',
                        'data' => $result['data']
                    ];
                } //用户输入密码
                elseif ($result['data']['status'] == '0') {
                    return [
                        'status' => 2,
                        'message' => '请用户输入密码',
                        'data' => $result['data']
                    ];
                } else {
                    return [
                        'status' => 3,
                        'message' => $result['data']
                    ];
                }
            }else{
                return [
                    'status' => 3,
                    'message' => $result['msg']
                ];
            }


        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //农商行退款
    public function refund1($data,$signkey)
    {
        try {
            $obj = new BaseController();
            $data['nonceStr']=$this->nonceStr();
            $post_data=$data;
            $string = $obj->getSignContent($post_data);
            $string = $string . '&key=' . $signkey;
            $sign = strtoupper(md5($string));
            $post_data['sign'] = $sign;
            $url = 'https://epos.ahrcu.com:3443/cposp/pay/refund';
            $this->add_refund_orders($data['itpOrderId'],$data['mchtRefundNo'],$data['refundAmount']/100);
            $re = $this->http_curl($url, json_encode($post_data));
             error_log(date('Y-m-d H:i:s')." 【农商行退款】： ".json_encode([$re])."\n\n", 3, "/tmp/". 'yinka'.date('Ymd').".log");

            $re = json_decode($re, true);
            //交易成功
            if ($re['refundStatus'] == 01) {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re
                ];
            }
            elseif ($re['refundStatus'] == 00) {
                return [
                    'status' => 2,
                    'message' => '正在退款中',
                    'data' => $re
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re,
                ];
            }

        } catch (\Exception $exception) {
             error_log(date('Y-m-d H:i:s')." 【农商行退款】： ".json_encode([$exception->getMessage()])."\n\n", 3, "/tmp/". 'yinka'.date('Ymd').".log");

            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //平安银行退款
    public function refund6($data)
    {
        try {
            $obj = new BaseController();
            $url = 'http://www.vipspt.cn/payOpen/refund.do';
            $re = $this->http_curl($url, $data);
            // file_put_contents('rrrr.log',var_export($data,true)."\r\n",FILE_APPEND);
            // file_put_contents('rrrr.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);
            //交易成功
            if ($re['data']['status'] == '11') {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re['data']
                ];
            }
            elseif ($re['status'] == '7') {
                return [
                    'status' => 2,
                    'message' => '正在退款中',
                    'data' => $re['data']
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re['data'],
                ];
            }
        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

     //扫呗退款
    public function refund3($data,$token)
    {
        try {
            $obj = new BaseController();
            $string = $obj->getSignContent1($data);
            $string = $string . '&access_token=' . $token;
            $sign = md5($string);
            $data['key_sign'] = $sign;
            $url = 'https://pay.lcsw.cn/lcsw/pay/100/refund';
            $re = $this->http_curl($url, json_encode($data));
            // file_put_contents('sao.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);

            //交易成功
            if ($re['result_code'] == '01') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re
                ];
            } //用户输入密码
            elseif ($re['result_code'] == '03') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //通联支付退款
    public function allin_refund($data,$prikey)
    {
        try {
            $obj = new BaseController();
            $sign=$obj->allin_sign($data,$prikey);
            $data['sign'] = urlencode($sign);
            $dataStr=$obj->allin_Params($data);
            $url = 'https://vsp.allinpay.com/apiweb/tranx/refund';
            $re = $this->allin_request($url, $dataStr);
            $re = json_decode($re, true);
            //交易成功
            if ($re['trxstatus'] == '0000') {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re,
                ];
            } //用户输入密码
            elseif ($re['trxstatus'] == '2008' || $re['trxstatus'] == '2000') {
                return [
                    'status' => 2,
                    'message' => '退款中',
                    'data' => $re,
                ];

            } else {
                return [
                    'status' => 3,
                    'message' => '支付失败',
                    'data' => $re,
                ];
            }
        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }

    //翼支付退款
    public function refund2($data)
    {
        try {
            $obj = new BaseController();
            $post_data=$data;
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $post_data['sign'] = $sign;
            $url = 'https://mapi.bestpay.com.cn/mapi/aggregatepay/offline/refund';
            $re = $this->http_curl($url, json_encode($post_data));
            file_put_contents('wingref.log',var_export($re,true)."\r\n",FILE_APPEND);
            $re = json_decode($re, true);
            //交易成功
            if ($re['result']['tradeStatus'] == 'SUCCESS') {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re['result'],
                ];
            } //用户输入密码
            elseif ($re['result']['tradeStatus'] == 'WAITFORPAY') {
                return [
                    'status' => 2,
                    'message' => '正在退款中',
                    'data' => $re['result'],
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $re['result'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //退款 0-系统错误 1-成功
    public function refund($data)
    {
        try {
           $out_trade_no = $data['out_trade_no'];
            $total_amount = $data['total_amount'];
            $order_amt=$total_amount*100;
            $mer_id=$data['apikey'];
            $post_data=array();
            $url = 'https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/return/V2';
            $refund_order='tuikuan'.date("His",time());
            //定义请求参数
            $biz_content=array(
                'mer_id'=>$mer_id,
                'out_trade_no'=>$out_trade_no,
                'reject_amt'=>"$order_amt",
                'trade_date'=>date("Ymd",time()),
                'reject_no'=>$refund_order,
                'oper_id'=>'123',
            );
            //组装参数
            $post_data=array('app_id'=>$data['appid'],'sign_type'=>'RSA2','charset'=>'UTF-8','format'=>'json','msg_id'=>time(),'timestamp'=>date("Y-m-d H:i:s",time()),'biz_content'=>json_encode($biz_content));
            $obj = new BaseController();
            //排序并拼接待签名字符串
            $respBizContentStr = $obj->buildOrderedSignStr('/api/mybank/pay/qrcode/scanned/return/V2',$post_data);
            //私钥加密
            $prikey=$data['signkey'];
            openssl_sign($respBizContentStr,$signature,"-----BEGIN PRIVATE KEY-----\n".$prikey."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA256);
            $post_data['sign'] =base64_encode($signature);
            $this->add_refund_orders($refund_order,$out_trade_no,$total_amount);
            $re = $this->doPost($url, $post_data,'UTF-8');
            $re = json_decode($re, true);

            //交易成功
            if ($re['response_biz_content']['return_code'] == '0') {
                \App\Common\PaySuccessAction::addCoupon($out_trade_no, $re['response_biz_content'], 'refund');
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re['response_biz_content'],
                ];
            } else {
                //重复查询
                sleep(3);
                $refundQuery=$this->refundQueryLianfu([
                    "out_trade_no"=>$out_trade_no,
                    "refund_no"=>$refund_order,
                    "apikey"=>$data['apikey'],
                    "appid"=>$data['appid'],
                    "signkey"=>$data["signkey"]
                ]);
                Log::channel("lianfu")->info("lianfuRefundQueryResult",$refundQuery);
                if($refundQuery["status"]==1){
                    return [
                        'status' => 1,
                        'message' => '退款成功',
                        'data' => "",
                    ];
                }
                return [
                    'status' => 3,
                    'message' => $re['response_biz_content'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    public function refundQueryLianfu(array $data)
    {
        $out_trade_no = $data['out_trade_no'];
        $mer_id=$data['apikey'];
        $url = 'https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/refundqry/V1';
        //定义请求参数
        $biz_content=[
            "mer_id"=>$mer_id,
            "out_trade_no"=>$out_trade_no,
            "outtrx_serial_no"=>$data["refund_no"]
        ];

        //组装参数
        $post_data=array('app_id'=>$data['appid'],'sign_type'=>'RSA2','charset'=>'UTF-8','format'=>'json','msg_id'=>time(),'timestamp'=>date("Y-m-d H:i:s",time()),'biz_content'=>json_encode($biz_content));
        $obj = new BaseController();
        //排序并拼接待签名字符串
        Log::channel("lianfu")->info("refundQueryLianfureq",[
                "req"=>$post_data
        ]);
        $respBizContentStr = $obj->buildOrderedSignStr('/api/cardbusiness/aggregatepay/b2c/online/refundqry/V1',$post_data);
        //私钥加密
        $prikey=$data['signkey'];
        openssl_sign($respBizContentStr,$signature,"-----BEGIN PRIVATE KEY-----\n".$prikey."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA256);
        $post_data['sign'] =base64_encode($signature);
        $re = $this->doPost($url, $post_data,'UTF-8');
        Log::channel("lianfu")->info("refundQueryLianfures",[
            "res"=>$re
        ]);
        $re = json_decode($re, true);
        //交易成功
        if ($re["response_biz_content"]['return_code'] == '0') {
            return [
                'status' => 1,
                'message' => '退款成功',
                'data' => $re["response_biz_content"],
            ];
        } else {
            return [
                'status' => 3,
                'message' => $re["response_biz_content"],
            ];
        }
    }

    //翼支付退款
    public function refund_query1($data)
    {
        try {
            $obj = new BaseController();
            $post_data=$data;
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $post_data['sign'] = $sign;
            $url = 'https://mapi.bestpay.com.cn/mapi/aggregatepay/refundQuery';
            $re = $this->http_curl($url, json_encode($post_data));
            $re = json_decode($re, true);
            //交易成功
            if ($re['result']['tradeStatus'] == 'SUCCESS' || $re['result']['tradeStatus'] == 'WAITFORPAY') {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re['result'],
                ];
            }else {
                return [
                    'status' => 3,
                    'message' => $re['result'],
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //退款查询 0-系统错误 1-成功 2-正在退款 3-失败
    public function refund_query($data)
    {
        try {
            $refund_trade_no = $data['refund_trade_no'];
            $sub_mch_id = $data['sub_mch_id'];
            $mch_id = $data['mch_id'];
            $pub_key = $data['pub_key'];
            $pri_key = $data['pri_key'];
            $date = $data['date'];

            $post_data = [
                'sub_mch_id' => $sub_mch_id,
                'refund_trade_no' => $refund_trade_no,
                'date' => $date,
            ];

            $method = '/openapi/merchant/pay/refund-query';
            $obj = new BaseController();
            $obj->mch_id = $mch_id;
            $obj->pub_key = $pub_key;
            $obj->pri_key = $pri_key;
            $re = $obj->api($post_data, $method, false);

            //系统错误
            if ($re['code'] != "0") {
                return [
                    'status' => 0,
                    'message' => $re['msg']
                ];
            }

            //业务成功
            if ($re['data']['trade_status'] != 3) {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re['data']
                ];
            } else {
                return [
                    'status' => 0,
                    'message' => '退款失败',
                    'data' => $re['data']
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //生成动态二维码-公共
    public function send_qr($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $total_amount = $data['total_amount'];
            $remark = $data['remark'];
            $notify_url = $data['notify_url'];
            $url = $data['request_url'];
            $returnParams = $data['return_params']; //原样返回
            $md_key = $data['md_key'];
            $mid = $data['mid'];
            $orgNo = $data['orgNo'];
            $payChannel = $data['payChannel'];

            $data = [
                'mid' => $mid,
                'totalFee' => $total_amount,
                'outTradeNo' => $out_trade_no,
                'nonceStr' => $out_trade_no,
                'payChannel' => $payChannel,
                'notifyUrl' => $notify_url,
                'orgNo' => $orgNo,
            ];

            $this->md_key = $md_key;
            $re = $this->execute($data, $url);
            //系统错误
            if ($re['resultCode'] == "fail") {
                return [
                    'status' => 0,
                    'message' => $re['errDes']
                ];
            }

            if ($re['resultCode'] == "success") {
                return [
                    'status' => 1,
                    'code_url' => $re['codeUrl'],
                    'message' => $re
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //静态码提交-公共
    public function qr_submit($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $total_amount = $data['total_amount'];
            $order_amt=$total_amount*100;
            $mer_id=$data['apikey'];
            $post_data=array();
            $url = 'https://gw.open.icbc.com.cn/api/cardbusiness/qrcode/qrgenerate/V3';
            //定义请求参数
            $biz_content=array(
                'mer_id'=>$mer_id,
                'out_trade_no'=>$out_trade_no,
                'order_amt'=>"$order_amt",
                'trade_date'=>date("Ymd",time()),
                'trade_time'=>date("His",time()),
                'pay_expire'=>'1000',
                'tporder_create_ip'=>$_SERVER['REMOTE_ADDR'],
                'notify_flag'=>'1',
                'notify_url'=>url('api/wincode/icbc_callback')
            );
            //组装参数
            $post_data=array('app_id'=>$data['appid'],'sign_type'=>'RSA2','charset'=>'UTF-8','format'=>'json','msg_id'=>time(),'timestamp'=>date("Y-m-d H:i:s",time()),'biz_content'=>json_encode($biz_content));
            $obj = new BaseController();
            //排序并拼接待签名字符串
            $respBizContentStr = $obj->buildOrderedSignStr('/api/cardbusiness/qrcode/qrgenerate/V3',$post_data);
            //私钥加密
            $prikey=$data['signkey'];
            openssl_sign($respBizContentStr,$signature,"-----BEGIN PRIVATE KEY-----\n".$prikey."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA256);
            $post_data['sign'] =base64_encode($signature);
            $re = $this->doPost($url, $post_data,'UTF-8');

            $re = json_decode($re, true);
            error_log(date('Y-m-d H:i:s')." 【工行主扫返回】： ".json_encode($re)."\n\n", 3, "/tmp/". 'icbc'.date('Ymd').".log");


            //系统错误
            if ($re['response_biz_content']['return_code'] != "0") {
                return [
                    'status' => 0,
                    'message' => '系统出错'
                ];
            }

            //如果是失败报备一下
            if ($re['response_biz_content']['return_code'] == "0") {
                return [
                    'status' => 1,
                    'message' => '返回成功',
                    'data' => $re['response_biz_content']

                ];
            }
        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //订单关闭
    public function order_close($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $url = $data['request_url'];
            $md_key = $data['md_key'];
            $mid = $data['mid'];
            $orgNo = $data['orgNo'];

            //请求数据
            $data = [
                'mid' => $mid,
                'nonceStr' => $out_trade_no,
                'outTradeNo' => $out_trade_no,
                'orgNo' => $orgNo,
            ];

            $this->md_key = $md_key;
            $re = $this->execute($data, $url);

            //系统错误
            if ($re['resultCode'] == "fail") {
                return [
                    'status' => 0,
                    'message' => $re['errDes']
                ];
            }

            //业务成功
            if ($re['resultCode'] == "success") {
                //交易成功
                return [
                    'status' => 1,
                    'message' => '关闭成功',
                    'data' => $re
                ];
            } else {
                return [
                    'status' => 0,
                    'message' => $re['errDes']
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage()
            ];
        }
    }

    /**
     * 32位随机数
     * @return string
     */
    public function nonceStr()
    {
        return md5(mt_rand(1000, 9999).time());
    }

        public function http_curl($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
//        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // post的变量
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            )
        );
        $output = curl_exec($ch);
        curl_close($ch);

        //返回数据
        return $output;
    }

    //翼支付加白查询
    public function get_Smooth($data,$url){
        $obj = new BaseController();
        $post_data=$data;
        $string = $obj->getSignContent($data);
        $sign=$this->createSign($string);
        $post_data['sign'] = $sign;
        $re = $this->http_curl($url, json_encode($post_data));
        $re=json_decode($re,true);
        if(!$re['result']['openFlag']){
            $post_array=array(
                'traceLogId'=>'wing'.time(),
                'agentMerchantCode'=>$data['signMerchantNo'],
                'merchantCode'=>$data['merchantCode'],
                'markProductType'=>'CYB',
                'markStatus'=>'MARKED',
                'prodCode'=>'20230831145538403273853213384704',
                'requestChannel'=>'ANHUI_API',
                'signMerchantNo'=>$data['signMerchantNo'],
                'agreeId'=>'20200909030100043101977613172787',
                'signType'=>'S002',
            );
            $re=$this->markMerchantProductForApi($post_array,'https://mapi.bestpay.com.cn/gapi/o2o/ruyi/app/markCYBProductForApi');
            return $re;
        }
    }

    public function markMerchantProductForApi($data,$url){
        $obj = new BaseController();
        $string = $obj->getSignContent($data);
        $sign=$this->createSign($string);
        $data['sign']=$sign;

        $data=json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

        $key='KrglKECpfXvOpGY3';
        $encryptData = openssl_encrypt($data, 'AES-128-CBC', $key,0,'b2owNVVDUllYT2I=');

        $encryptKey=$this->createSignf($key);//aeskey进行RSA加密
        $array=array(
            'encryptData'=>$encryptData,
            'encryptKey'=>$encryptKey,
            'signMerchantNo'=>'3178035630163868',
            'encyType'=>'C010',
        );

        $re = $this->http_curl($url, json_encode($array,JSON_UNESCAPED_SLASHES));
        return $re;
        // $re=json_decode($re,true);
        // $str = mb_convert_encoding($re['result']['encryptKey'], 'UTF-8');
        // $strData = mb_convert_encoding($re['result']['encryptData'], 'UTF-8');
        // $decoded = base64_decode(str_replace(' ', '+', $str));
        // $encryptKey=$this->createSignj($decoded);//aeskey进行RSA加密
        // $data1 = openssl_decrypt($strData, 'AES-128-CBC', $encryptKey,0, 'b2owNVVDUllYT2I=');
        // return $data1;
    }

    public function get_sub_merchant($data){
        $url='https://mapi.bestpay.com.cn/mapi/outside/agent/merchantInput/queryMixInputInfo';
        $obj = new BaseController();
        $string = $obj->getSignContent($data);
        $sign=$this->createSign($string);
        $data['sign']=$sign;

        $data=json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

        $key='KrglKECpfXvOpGY3';
        $encryptData = openssl_encrypt($data, 'AES-128-CBC', $key,0,'b2owNVVDUllYT2I=');

        $encryptKey=$this->createSignf($key);//aeskey进行RSA加密
        $array=array(
            'encryptData'=>$encryptData,
            'encryptKey'=>$encryptKey,
            'merchantNo'=>'3178035630163868'
        );
        $re = $this->http_curl($url, json_encode($array,JSON_UNESCAPED_SLASHES));
        $re=json_decode($re,true);
        $str = mb_convert_encoding($re['result']['encryptKey'], 'UTF-8');
        $strData = mb_convert_encoding($re['result']['encryptData'], 'UTF-8');
        $decoded = base64_decode(str_replace(' ', '+', $str));
        $encryptKey=$this->createSignj($decoded);//aeskey进行RSA加密
        $data1 = openssl_decrypt($strData, 'AES-128-CBC', $encryptKey,0, 'b2owNVVDUllYT2I=');
        $data1=json_decode($data1,true);
        return $data1['aggregateSuccessResultResDTOList'];
    }

    //翼支付对账关系绑定
    public function verifyFileRelationAggregateCfg($url,$data)
    {
        try {
            $obj = new BaseController();
            $string = $obj->getSignContent($data);
            $sign=$this->createSign($string);
            $data['sign'] = $sign;
            $post_data=json_encode($data);
            $re = $this->http_curl($url, $post_data);
            return $re;

        } catch (\Exception $exception) {
            return ['status' => 0, 'message' => $exception->getMessage(),];
        }
    }
}
